package com.xpengplayer.update;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 * 下载完成广播接收器
 * 用于监听APK下载完成事件并触发安装
 */
public class DownloadCompleteReceiver extends BroadcastReceiver {
    private static final String TAG = "DownloadCompleteReceiver";
    private static final String UPDATE_APK_DIR = "XpengPlayer/updates";
    private static final String UPDATE_APK_NAME = "XpengPlayer_update.apk";
    
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
            // 获取下载完成的ID
            long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (downloadId != -1) {
                // 处理下载完成的APK
                handleDownloadCompleted(context, downloadId);
            }
        }
    }
    
    /**
     * 处理下载完成的APK
     */
    private void handleDownloadCompleted(Context context, long downloadId) {
        try {
            // 获取下载文件的URI
            DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            if (manager != null) {
                Uri downloadUri = manager.getUriForDownloadedFile(downloadId);
                
                if (downloadUri != null) {
                    // 获取文件的实际路径
                    String filePath = getRealPathFromUri(context, downloadUri);
                    if (filePath != null) {
                        File apkFile = new File(filePath);
                        if (apkFile.exists() && apkFile.isFile()) {
                            // 安装APK
                            installApk(context, apkFile);
                        } else {
                            // 尝试直接从下载目录获取文件
                            installFromDownloadDirectory(context);
                        }
                    } else {
                        // 如果无法获取真实路径，尝试从下载目录获取
                        installFromDownloadDirectory(context);
                    }
                } else {
                    // 尝试从下载目录获取文件
                    installFromDownloadDirectory(context);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "处理下载完成的APK时出错: " + e.getMessage());
            Toast.makeText(context, "处理更新包时出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 从下载目录安装APK
     */
    private void installFromDownloadDirectory(Context context) {
        File apkFile = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                UPDATE_APK_DIR + File.separator + UPDATE_APK_NAME
        );
        
        if (apkFile.exists() && apkFile.isFile()) {
            installApk(context, apkFile);
        } else {
            Log.e(TAG, "APK文件不存在: " + apkFile.getAbsolutePath());
            Toast.makeText(context, "更新包下载失败或文件路径错误", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 安装APK文件
     */
    private void installApk(Context context, File apkFile) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri apkUri;
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // Android 7.0及以上需要使用FileProvider
                apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                apkUri = Uri.fromFile(apkFile);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "安装APK失败: " + e.getMessage());
            Toast.makeText(context, "安装更新失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 从URI获取真实文件路径
     */
    private String getRealPathFromUri(Context context, Uri uri) {
        String filePath = null;
        
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
                // 处理Document类型的URI
                String docId = DocumentsContract.getDocumentId(uri);
                if (isExternalStorageDocument(uri)) {
                    String[] split = docId.split(":");
                    String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        filePath = Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                } else if (isDownloadsDocument(uri)) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                    filePath = getDataColumn(context, contentUri, null, null);
                } else if (isMediaDocument(uri)) {
                    String[] split = docId.split(":");
                    String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    String selection = "_id=?";
                    String[] selectionArgs = new String[] { split[1] };
                    filePath = getDataColumn(context, contentUri, selection, selectionArgs);
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                // 处理Content类型的URI
                filePath = getDataColumn(context, uri, null, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                // 处理File类型的URI
                filePath = uri.getPath();
            }
        } catch (Exception e) {
            Log.e(TAG, "获取文件真实路径时出错: " + e.getMessage());
        }
        
        return filePath;
    }
    
    /**
     * 获取数据列的值
     */
    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = "_data";
        String[] projection = { column };
        
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            Log.e(TAG, "查询数据库时出错: " + e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        
        return null;
    }
    
    /**
     * 判断URI是否为外部存储文档
     */
    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
    
    /**
     * 判断URI是否为下载文档
     */
    private boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
    
    /**
     * 判断URI是否为媒体文档
     */
    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}